package com.dx.mes.common.core.rabbitmq;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;

public class BaseConnFactory {
    private String rabbitMQHost;
    private Integer rabbitMQPort;
    private String rabbitMQUserName;
    private String rabbitMQUserPassword;
	public String getRabbitMQHost() {
		return rabbitMQHost;
	}
	public void setRabbitMQHost(String rabbitMQHost) {
		this.rabbitMQHost = rabbitMQHost;
	}
	public Integer getRabbitMQPort() {
		return rabbitMQPort;
	}
	public void setRabbitMQPort(Integer rabbitMQPort) {
		this.rabbitMQPort = rabbitMQPort;
	}
	public String getRabbitMQUserName() {
		return rabbitMQUserName;
	}
	public void setRabbitMQUserName(String rabbitMQUserName) {
		this.rabbitMQUserName = rabbitMQUserName;
	}
	public String getRabbitMQUserPassword() {
		return rabbitMQUserPassword;
	}
	public void setRabbitMQUserPassword(String rabbitMQUserPassword) {
		this.rabbitMQUserPassword = rabbitMQUserPassword;
	}
    
    /**
     * 创建连接
     * @throws IOException 
     */
	public ConnectionFactory creatConnectionFactory() throws IOException{
		ConnectionFactory connFactory = new ConnectionFactory();
        //rabbitmq监听IP
		connFactory.setHost(rabbitMQHost);
        //rabbitmq监听默认端口  
		connFactory.setPort(rabbitMQPort);
        //设置访问的用户  
		connFactory.setUsername(rabbitMQUserName);
		connFactory.setPassword(rabbitMQUserPassword);
        return connFactory;
	}

	public void addSAPREQProc(String qName, String sapreq) throws Exception
	{
		Connection connection = creatConnectionFactory().newConnection();

		Channel channel = connection.createChannel();
		try
		{
			channel.queueDeclare(qName, true, false, false, null);

			channel.basicPublish("", qName, new AMQP.BasicProperties(), sapreq.getBytes("UTF-8"));
		} catch (Exception e) {
			throw e;
		} finally {
			if (channel.isOpen()) {
				channel.close();
			}

			if (connection.isOpen())
				connection.close();
		}
	}
	
}
